package com.example;

import com.alibaba.fastjson.JSONObject;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import java.util.List;

public class ExampleMain {
    public static void main(String[] args) {
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("my-persistence-unit");
        persistDepartment(emf);
        persistEmployee(emf);
        getAllEmployees(emf);
        emf.close();
    }
    private static void getAllEmployees(EntityManagerFactory emf){
        System.err.println("-- select all employee query ---");
        EntityManager em = emf.createEntityManager();
        Query query = em.createQuery("select e from Employee e");
        List<Employee> employees = query.getResultList();
        for (Employee employee : employees) {
            System.err.println(JSONObject.toJSONString(employee,false));
        }
    }
    private static void persistEmployee(EntityManagerFactory emf){
        System.err.println("--- persisting employee ---");
        EntityManager em = emf.createEntityManager();
        Department department = em.getReference(Department.class,1);
        Employee employee1 = new Employee("Joe",department);
        Employee employee2 = new Employee("Jackie",department);
        em.getTransaction().begin();
        em.persist(employee1);
        em.persist(employee2);
        em.getTransaction().commit();
        em.close();
    }
    private static void persistDepartment(EntityManagerFactory emf){
        System.err.println("--- persisting department ---");
        Department department = new Department("Admin");
        EntityManager em = emf.createEntityManager();
        em.getTransaction().begin();
        em.persist(department);
        em.getTransaction().commit();
        em.close();
    }
}
